package cn.project.dao;

import cn.project.model.User;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class UserImple extends HibernateDaoSupport implements UserDao {
    public void addUser(User user) {
        getHibernateTemplate().save(user);
    }

    public void delUser(int userid) {
        /*回调get中返回的对象*/
      getHibernateTemplate().delete(get(userid));
    }

    public void updateUser(User user) {
        getHibernateTemplate().update(user);
    }

    public User get(int userid) {

        return getHibernateTemplate().get(User.class,userid);
    }

    public List searchUser(final User user) {
    List list=super.getHibernateTemplate().executeFind(
            new HibernateCallback () {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    Criteria cri=session.createCriteria(User.class);
                    if(user !=null){
                        if(user.getPassword()!=null && user.getPassword().trim().length()>0){
                             cri.add(Restrictions.like("password",user.getPassword(), MatchMode.ANYWHERE));
                        }
                    }
                    return cri.list();
                }
            }
    );
        return list;
    }

    public List searchUser(String hql) {
        return getHibernateTemplate().find(hql);
    }
}
